package top.yokey.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.fragment.app.Fragment;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import top.yokey.android.R;
import top.yokey.android.activity.DynamicAddActivity;
import top.yokey.android.adapter.CircleAdapter;
import top.yokey.android.base.App;
import top.yokey.android.http.BaseCallBack;
import top.yokey.android.http.HttpHelp;
import top.yokey.android.http.CircleBean;
import top.yokey.android.view.PullRefreshView;

public class HomeFragment extends Fragment {

    private ArrayList<CircleBean> arrayList = new ArrayList<>();
    private CircleAdapter adapter = new CircleAdapter(arrayList);

    private int page = 1;
    private int position = 0;
    private String circleId = "";
    private String replyId = "";
    private String replyNickname = "";

    private AppCompatImageView addImageView;
    private PullRefreshView mainPullRefreshView;

    private LinearLayoutCompat commitLinearLayout;
    private AppCompatEditText contentEditText;
    private AppCompatTextView sendTextView;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        addImageView = root.findViewById(R.id.addImageView);
        mainPullRefreshView = root.findViewById(R.id.mainPullRefreshView);

        commitLinearLayout = root.findViewById(R.id.commitLinearLayout);
        contentEditText = root.findViewById(R.id.contentEditText);
        sendTextView = root.findViewById(R.id.sendTextView);

        mainPullRefreshView.setLinearLayoutManager();
        mainPullRefreshView.setAdapter(adapter);

        initEvent();
        getData();
        return root;
    }

    private void initEvent() {

        addImageView.setOnClickListener(view -> startActivity(new Intent(getActivity(), DynamicAddActivity.class)));

        adapter.setOnItemClickListener(new CircleAdapter.OnItemClickListener() {

            @Override
            public void onDelete(int position, CircleBean bean) {
                if (bean.getMemberId() == App.get().getMemberBean().getMemberId()) {
                    new AlertDialog.Builder(getActivity())
                            .setIcon(R.mipmap.ic_avatar)
                            .setTitle("确认您的选择")
                            .setMessage("删除此条动态？")
                            .setCancelable(false)
                            .setPositiveButton("确认", (dialogInterface, i) -> {
                                //请求删除评论接口
                                HttpHelp.get().ready("circle", "delete")
                                        .add("id", bean.getCircleId() + "")
                                        .get(new BaseCallBack() {
                                            @Override
                                            public void onSuccess(String data) {
                                                arrayList.remove(position);
                                                adapter.notifyDataSetChanged();
                                            }

                                            @Override
                                            public void onError(String reason) {
                                                Toast.makeText(getActivity(), reason, Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            })
                            .setNegativeButton("取消", null)
                            .show();
                }
            }

            @Override
            public void onClick(int position, CircleBean bean) {
                System.out.println(position + "|" + bean.getCircleContent());
            }

            @Override
            public void onClickCommit(int position, CircleBean bean) {
                HomeFragment.this.position = position;
                circleId = bean.getCircleId() + "";
                replyId = "-1";
                contentEditText.setHint("说点什么...");
                commitLinearLayout.setVisibility(View.VISIBLE);//点击评论标签时显示编辑框
            }

            @Override
            public void onClickReply(int position, int positionComment, CircleBean.CommitDataDTO bean) {
                //这是回复他人评论的操作
                HomeFragment.this.position = position;
                circleId = bean.getCircleId() + "";
                replyId = bean.getCommitId() + "";
                replyNickname = bean.getMemberNickname();
                contentEditText.setHint("回复@" + bean.getMemberNickname());
                commitLinearLayout.setVisibility(View.VISIBLE);//点击评论标签时显示编辑框
            }

            @Override
            public void onLongClickCommit(int position, int positionComment, CircleBean.CommitDataDTO bean) {
                if (bean.getMemberId() == App.get().getMemberBean().getMemberId()) {
                    new AlertDialog.Builder(getActivity())
                            .setIcon(R.mipmap.ic_avatar)
                            .setTitle("确认您的选择")
                            .setMessage("删除此条评论？")
                            .setCancelable(false)
                            .setPositiveButton("确认", (dialogInterface, i) -> {
                                //请求删除评论接口
                                HttpHelp.get().ready("circle", "deleteCommit")
                                        .add("id", bean.getCommitId() + "")
                                        .get(new BaseCallBack() {
                                            @Override
                                            public void onSuccess(String data) {
                                                arrayList.get(position).getCommitData().remove(positionComment);
                                                adapter.notifyDataSetChanged();
                                            }

                                            @Override
                                            public void onError(String reason) {
                                                Toast.makeText(getActivity(), reason, Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            })
                            .setNegativeButton("取消", null)
                            .show();
                }
            }
        });

        sendTextView.setOnClickListener(view -> {
            String content = contentEditText.getText().toString();
            if (content.isEmpty()) {
                Toast.makeText(getContext(), "请输入内容", Toast.LENGTH_SHORT).show();
            }
            HttpHelp.get().ready("circle", "commit")
                    .add("id", circleId)
                    .add("reply_id", replyId)
                    .add("content", content)
                    .get(new BaseCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            commitLinearLayout.setVisibility(View.GONE);
                            contentEditText.setText("");
                            CircleBean.CommitDataDTO commitDataDTO = new CircleBean.CommitDataDTO();
                            commitDataDTO.setCircleId(Integer.parseInt(circleId));
                            commitDataDTO.setCommitContent(content);
                            commitDataDTO.setMemberNickname(App.get().getMemberBean().getMemberNickname());
                            if (!replyId.equals("-1")) {
                                commitDataDTO.setReplyId(Integer.parseInt(replyId));
                                commitDataDTO.setReplyMemberNickname(replyNickname);
                            } else {
                                commitDataDTO.setReplyId(-1);
                            }
                            arrayList.get(position).getCommitData().add(commitDataDTO);
                            adapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onError(String reason) {
                            Toast.makeText(getActivity(), reason, Toast.LENGTH_SHORT).show();
                        }
                    });
        });

        mainPullRefreshView.setOnRefreshListener(new PullRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                arrayList.clear();
                adapter.notifyDataSetChanged();
                mainPullRefreshView.setCanLoadMore(true);
                getData();
            }

            @Override
            public void onLoadMore() {
                getData();
            }
        });

        mainPullRefreshView.setOnClickListener(view -> {
            //如果没有数据则执行读取数据的方法
            if (mainPullRefreshView.isError() || arrayList.size() == 0) {
                page = 1;
                getData();
            }
        });

    }

    //自定义方法

    private void getData() {

        mainPullRefreshView.setLoad();//将组件设置为加载状态，去除网络请求缓慢地影响
        CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                HttpHelp.get().ready("circle", "getList")
                        .add("page", page + "")
                        .get(new BaseCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                try {
                                    JSONArray jsonArray = new JSONArray(data);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        arrayList.add(new Gson().fromJson(jsonArray.getString(i), CircleBean.class));
                                    }
                                    //确定分页是否自加
                                    if (jsonArray.length() == 20) {
                                        page++;
                                    } else {
                                        //禁用加载更多的功能
                                        mainPullRefreshView.setCanLoadMore(false);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                adapter.notifyDataSetChanged();//通知适配器，数据有变动
                                //读完数据完成之后的操作
                                //将刷新状态取消
                                mainPullRefreshView.setComplete();
                            }

                            @Override
                            public void onError(String reason) {
                                if (adapter.getItemCount() == 0) {
                                    mainPullRefreshView.setError(reason);
                                } else {
                                    Toast.makeText(App.get(), reason, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

            }
        }.start();
    }

}
